package com.code.telegram.services.impl;

import com.code.enums.CacheKeyEnum;
import com.code.telegram.configs.redis.RedisHandler;
import com.code.telegram.services.SmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 验证码业务聚合服务层
 *
 * @author xiaoyaowang
 */
@Service
public class SmsServiceImpl implements SmsService {

    private static Logger log = LoggerFactory.getLogger(SmsServiceImpl.class);

    private static final int SEND_CODE_MAX_TIMES = 3;

    private final String URL = "http://hk.5c.com.cn/api/send/index.php?username=13632735345&password_md5=1beecf22cce3afcaf55bd41e1f366af5&apikey=04329be860caa9687d801bacb238cce3&encode=UTF-8";

    @Value("${sms.prefix}")
    private String prefix;

    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private RedisHandler redisHandler;

    /**
     * 发送短信，开启异步支持，不需要同步
     *
     * @param phone   手机号
     * @param context 发送内容
     * @throws UnsupportedEncodingException 不支持编码异常
     */
    @Async
    @Override
    public void sendSms(String phone, String context) throws UnsupportedEncodingException {
        //设置某一个手机发送短信的时间间隔为60秒
        if (redisHandler.hasKey(CacheKeyEnum.SMS_SEND_INTERVAL.formatKey(phone))) {
            log.info("同一个手机号间隔60秒发送短信，避免恶意攻击短信接口！");
            return;
        }
        redisHandler.incr(CacheKeyEnum.SMS_SEND_TIMES_ONE_DAY.formatKey(phone));
        if ((int) redisHandler.get(CacheKeyEnum.SMS_SEND_TIMES_ONE_DAY.formatKey(phone)) > SEND_CODE_MAX_TIMES) {
            log.info("同一个手机号一天只能发3次，避免恶意攻击短信接口！");
            return;
        }
        redisHandler.expire(CacheKeyEnum.SMS_SEND_TIMES_ONE_DAY.formatKey(phone), CacheKeyEnum.SMS_SEND_TIMES_ONE_DAY.sec());

        context = prefix + context;

        context = URLEncoder.encode(context, "UTF-8");

        String url = URL + "&mobile=" + phone + "&content=" + context;

        String result = restTemplate.getForObject(url, String.class);

        log.info("sendSms url is {}, result is {}", url, result);

        redisHandler.set(CacheKeyEnum.SMS_SEND_INTERVAL.formatKey(phone), context, CacheKeyEnum.SMS_SEND_INTERVAL.sec());
    }

}
